import {BaseResponse} from "../../types/text";
import request from "../../utils/request";

// 定义接口返回类型
export interface ApiResponse<T = any> {
    code: number;
    data: T | null;
    message: string;
}

// 定义上传文本的参数类型
export interface UploadTextParams {
    title: string;
    content: string;
}


// 定义接口参数类型
export interface TextQueryParams {
    content?: string;
    current?: number;
    fileType?: number;
    language?: string;
    pageSize?: number;
}

// 定义响应数据类型
export interface TextDataResponseVO {
    content: string;
    title: string;
    createdAt: string;
    creatorId: number;
    filePath: string;
    fileType: number;
    language: string;
    textId: number;
    updatedAt: string;
    userId: number;
}

// 定义分页响应类型
export interface PageResponse {
    current: number;
    pages: number;
    records: TextDataResponseVO[];
    size: number;
    total: number;
}

// 相似度计算请求参数
export interface SimilarityRequestDTO {
    textId1: number;
    textId2: number;
    algorithmId: number;
}

// 相似度计算返回数据
export interface SimilarityResponseDTO {
    resultId: number | null;
    textId1: number | null;
    textId2: number | null;
    algorithmId: number | null;
    score: number;
    comparisonType: string | null;
    createdAt: string | null;
    chartData: {
        similarityGauge: {
            score: number;
            thresholds: {
                high: number;
                low: number;
                medium: number;
            };
        };
        wordFrequency: {
            text1Frequencies: number[];
            text2Frequencies: number[];
            labels: string[];
        };
    };
    similarSegments: string;
    differentSegments: string;
    analysisDetails: {
        text1Length: number;
        text2Length: number;
        commonTermsCount: number;
        uniqueText1Count: number;
        uniqueText2Count: number;
        topCommonWords: string[];
    };
    reportPath: string | null;
    reportStatus: string | null;
}


// 分页查询参数接口
interface PageAnalysisParams {
    pageNo: number;
    pageSize: number;
}

// 分析记录接口
interface AnalysisRecord {
    resultId: number;
    textId1: number;
    textId2: number;
    algorithmId: number;
    algorithmName: string;
    algorithmConfigName: string;
    score: number;
    createdAt: string;
}



// 相似度结果详情接口
interface SimilarityResult {
    resultId: number;
    textId1: number;
    textId2: number;
    algorithmId: number;
    score: number;
    comparisonType: number;
    createdAt: string;
    creatorId: number;
    modifierId: number;
    updatedAt: string;
    isDeleted: number;
    chartData: {
        similarityGauge: {
            score: number;
            thresholds: {
                high: number;
                low: number;
                medium: number;
            };
        };
        wordFrequency: {
            text1Frequencies: number[];
            text2Frequencies: number[];
            labels: string[];
        };
    };
    analysisDetails: {
        text1Length: number;
        text2Length: number;
        commonTermsCount: number;
        uniqueText1Count: number;
        uniqueText2Count: number;
        topCommonWords: string[];
    };
    similarSegments: string;
    differentSegments: string;
    reportPath: string;
    reportStatus: number;
}

// 分页响应接口
interface PageResponseForResult<T> {
    pageNo: number;
    pageSize: number;
    result: T[];
    total: number;
    totalPages: number;
    start: number;
}
export const textApi = {
    /**
     * 上传文本
     * @param params
     */
    uploadText: async (params: UploadTextParams): Promise<ApiResponse> => {
        try {
            // 打印请求参数
            console.log('发送上传请求参数:', params);

            // 使用 axios 的 response.data 获取实际响应数据
            const { data } = await request.post('/api/texts/uploadtext', params);

            // 打印完整响应
            console.log('完整响应数据:', data);

            // 确保返回一个合法的 ApiResponse 对象
            return {
                code: data?.code ?? 200,
                data: data?.data ?? null,
                message: data?.message ?? '操作成功'
            };
        } catch (error) {
            console.error('上传请求失败:', error);
            throw error;
        }
    },
    /**
     * 上传文件
     * @param file
     */
    uploadFile: async (file: File) => {
        const formData = new FormData();
        formData.append('file', file);
        const response = await request.post<ApiResponse>('/api/texts/uploadfile', formData, {
            headers: {
                'Content-Type': 'multipart/form-data',
            },
        });
        return response.data;  // 返回响应数据而不是整个响应对象
    },

    /**
     * 分页查询
     * @param params
     */
    getTextsByPage: async (params: TextQueryParams) => {
        try {
            const response = await request.get<any>('/api/texts/page', {
                params: {
                    ...params,
                    current: params.current || 1,
                    pageSize: params.pageSize || 10
                }
            });
            console.log('API原始响应:', response);
            return response.data;
        } catch (error) {
            console.error('API请求错误:', error);
            throw error;
        }
    },
    // 删除文本
    deleteText: async (textId: number) => {
        return request.delete<any>(`/api/texts/delete/${textId}`);
    },
    // 获取文本详情
    getTextById: async (textId: number) => {
        const response = await request.get<ApiResponse<TextDataResponseVO>>(`/api/texts/getTextById/${textId}`);
        return response.data;
    },

    /**
     * 计算文本相似度
     * @param params 包含textId1、textId2和algorithmId的请求参数
     * @returns Promise<BaseResponse<SimilarityResponseDTO>>
     */
    computeTextSimilarity: async (params: SimilarityRequestDTO): Promise<BaseResponse<SimilarityResponseDTO>> => {
        try {
            // 使用 request.post 发送请求
            const response = await request.post<BaseResponse<SimilarityResponseDTO>>(
                '/api/texts/compute',
                params
            );

            // 返回响应数据
            return response.data;
        } catch (error) {
            console.error('计算文本相似度失败:', error);
            // 抛出错误，让调用者处理
            throw error;
        }
    },

    /**
     * 分页查询文本相似度分析历史
     * @param params 分页参数
     * @returns Promise<BaseResponse<PageResponse<AnalysisRecord>>>
     */
    pageAnalysis: async (params: PageAnalysisParams): Promise<BaseResponse<PageResponseForResult<AnalysisRecord>>> => {
        try {
            console.log('发送分页查询请求参数:', params);

            const response = await request.get<BaseResponse<PageResponseForResult<AnalysisRecord>>>(
                '/api/tasks/pageAnalysis',
                {
                    params: {
                        pageNo: params.pageNo || 1,
                        pageSize: params.pageSize || 10
                    }
                }
            );

            console.log('分页查询响应数据:', response.data);

            // 格式化返回数据中的时间
            if (response.data?.data?.result) {
                response.data.data.result = response.data.data.result.map(record => ({
                    ...record,
                    createdAt: record.createdAt ?
                        new Date(record.createdAt).toISOString().slice(0, 19).replace('T', ' ') :
                        ''
                }));
            }

            return response.data;
        } catch (error) {
            console.error('分页查询分析历史失败:', error);
            throw error;
        }
    },

    /**
     * 根据结果ID获取详细分析结果
     * @param resultId 结果ID
     * @returns Promise<BaseResponse<SimilarityResult>>
     */
    getResultById: async (resultId: number): Promise<BaseResponse<SimilarityResult>> => {
        try {
            const response = await request.get<BaseResponse<SimilarityResult>>(
                '/api/tasks/getResultById',
                {
                    params: { resultId }
                }
            );
            console.log('根据resultId获取结果:', response.data);

            // // 添加数据结构验证和默认值
            // if (response.data?.data) {
            //     const result = response.data.data;
            //     // 确保必要的数据结构存在
            //     result.chartData = result.chartData || {
            //         similarityGauge: {
            //             score: 0,
            //             thresholds: { high: 0.7, medium: 0.4, low: 0.3 }
            //         },
            //         wordFrequency: {
            //             text1Frequencies: [],
            //             text2Frequencies: [],
            //             labels: []
            //         }
            //     };
            //     result.analysisDetails = result.analysisDetails || {
            //         text1Length: 0,
            //         text2Length: 0,
            //         commonTermsCount: 0,
            //         uniqueText1Count: 0,
            //         uniqueText2Count: 0,
            //         topCommonWords: []
            //     };
            // }

            return response.data;
        } catch (error) {
            console.error('获取分析结果详情失败:', error);
            throw error;
        }
    }
};


